package megrez.common.core.util;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

import lombok.extern.slf4j.Slf4j;

/**
 * TODO
 * 
 * @author Lucky Yang
 * @since 0.0.1
 */
@Slf4j
public class Nap {
    private final Duration duration;
    private final boolean isAfter;

    private Nap(Duration duration, boolean isAfter) {
        this.duration = duration;
        this.isAfter = isAfter;
    }

    public void doEmpty() {
        this.doThis(() -> log.info("Nap.doEmpty"));
    }

    public void doThis(Runnable runnable) {
        try {
            if (!isAfter) {
                runnable.run();
            }
            TimeUnit.MILLISECONDS.sleep(duration.toMillis());
            if (isAfter) {
                runnable.run();
            }
        } catch (InterruptedException e) {
            log.warn("Interrupted", e);
            Thread.currentThread().interrupt();
        }

    }

    /**
     * 睡眠时间之后
     * 
     * @param duration
     * @return
     */
    public static Nap after(Duration duration) {
        return new Nap(duration, true);
    }

    public static Nap before(Duration duration) {
        return new Nap(duration, false);
    }
}
